package com.example.base.crash

import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.base.R
import com.example.base.crash.CrashLogFragment.LogAdapter.LogVH
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.util.*

class CrashLogFragment : Fragment() {
    var recyclerView: RecyclerView? = null
    var fileReadHandler: Handler? = null
    var uiHandler = Handler()
    var adapter = LogAdapter()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_crash_log, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        var recyclerView1: RecyclerView = view.findViewById(R.id.recyclerview)
        recyclerView=recyclerView1;
        recyclerView!!.setLayoutManager(LinearLayoutManager(context, RecyclerView.VERTICAL, false))
        recyclerView!!.setAdapter(adapter)
        val decoration = DividerItemDecoration(context, RecyclerView.VERTICAL)
        decoration.setDrawable(resources.getDrawable(R.drawable.list_divider_horizontal))
        recyclerView!!.addItemDecoration(decoration)
        val thread: HandlerThread = object : HandlerThread("crash_log_read") {
            override fun onLooperPrepared() {
                super.onLooperPrepared()
                fileReadHandler = Handler(looper)
                readFileList()
            }
        }
        thread.start()
    }

    private fun readFileList() {
        fileReadHandler!!.post(Runnable {
            val dir = CrashLog.crashLogDir(context) ?: return@Runnable
            val file = File(dir)
            val fs = Arrays.asList(*file.listFiles())
            Collections.sort(fs) { o1, o2 -> (o2.lastModified() - o1.lastModified()).toInt() }
            val logs: MutableList<Log> = ArrayList()
            for (f in fs) {
                logs.add(Log(f, f.name, null))
            }
            setFileList(logs)
        })
    }

    private fun setFileList(logs: List<Log>) {
        uiHandler.post { adapter.setFileList(logs) }
    }

    private fun readFileContent(file: File) {
        fileReadHandler!!.post {
            try {
                val content = read(file)
                update(file, content)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun update(file: File, content: String?) {
        if (content == null) {
            return
        }
        uiHandler.post(Runnable {
            for (log in adapter.logs!!) {
                if (log.file === file) {
                    log.content = content
                    adapter.notifyDataSetChanged()
                    return@Runnable
                }
            }
        })
    }

    @Throws(Exception::class)
    private fun read(file: File): String {
        val reader = BufferedReader(InputStreamReader(FileInputStream(file)))
        var line: String?
        val builder = StringBuilder(file.length().toInt())
        while (reader.readLine().also { line = it } != null) {
            builder.append(line)
            builder.append("\n")
        }
        return builder.toString()
    }

    inner class LogAdapter : RecyclerView.Adapter<LogVH>() {
        var logs: List<Log>? = null
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LogVH {
            return LogVH()
        }

        override fun onBindViewHolder(holder: LogVH, position: Int) {
            holder.title.tag = position
            val log = getData(position)
            holder.copy.tag = log.content
            holder.title.text = log.title
            if (log.content == null) {
                holder.content.visibility = View.GONE
                holder.copy.visibility = View.INVISIBLE
            } else {
                holder.content.text = log.content
                holder.content.visibility = View.VISIBLE
                holder.copy.visibility = View.VISIBLE
            }
        }

        protected fun getData(position: Int): Log {
            return logs!![position]
        }

        override fun getItemCount(): Int {
            return if (logs == null) 0 else logs!!.size
        }

        fun setFileList(fs: List<Log>?) {
            logs = fs
            notifyDataSetChanged()
        }

        inner class LogVH : RecyclerView.ViewHolder(
            LayoutInflater.from(context).inflate(R.layout.item_crash_log, recyclerView, false)
        ) {
            var title: TextView
            var content: TextView
            var copy: TextView

            init {
                title = itemView.findViewById(R.id.title)
                content = itemView.findViewById(R.id.content)
                copy = itemView.findViewById(R.id.copy)
                title.setOnClickListener { v ->
                    val position = v.tag as Int
                    if (logs!![position].content == null) {
                        readFileContent(logs!![position].file)
                    }
                }
                copy.setOnClickListener { v ->
                    val log = v.tag as String
                    val cmb =
                        v.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    cmb.text = log
                    Toast.makeText(v.context, "已经复制到粘贴板", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    inner class Log(var file: File, var title: String, var content: String?)
}